<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>倒计时广告</title>
    <style>
        *{
            margin: 0;
            padding: 0;
        }
        #ad{
            width: 500px;
            height: 400px;
            border: 1px solid #ccc;
            position: relative;
            /* left: 50px;
            top: 100px; */
            /* margin: 0 auto; */
            /* top:50%;
            left:50%;
            transform:translate(-50%, -50%); */
        }
        #box{
            width: 120px;
            height: 40px;
            background: #d8d8d8;
            position: absolute;
            left: 10px;
            top: 10px;
        }
        #close{
            position: absolute;
            right: 5px;
            top: 5px;
            cursor: pointer;
        }
    </style>
</head>
<body>
    <div id="ad">
        <p id="close">X</p>
        <P id="box">倒计时：<span id="time">5秒</span></P>
    </div>
</body>
<script>
    /*
        需求：倒计时广告
            * 广告居中:js
                * (获取屏幕宽度 - 盒子宽度)/2 left:水平居中
                * (获取屏幕宽度 - 盒子宽度)/2 top:垂直居中
            * 倒计时：5秒倒计时，倒计时结束后，就关掉定时器，隐藏广告
            * 主动点击x：马上关掉定时器并隐藏广告
    */

    //1.广告居中
    var ad = document.getElementById('ad');
    var time = document.getElementById('time');
    var close = document.getElementById('close');

    var ileft = (window.innerWidth - ad.offsetWidth)/2;
    var itop = (window.innerHeight - ad.offsetHeight)/2;

    ad.style.left = ileft + 'px';
    ad.style.top = itop + 'px';


    //2.倒计时：5秒倒计时，倒计时结束后，就关掉定时器，隐藏广告
    var num = 5;
    var timer = setInterval(function() {
        num--;
        if(num < 0) {
            clearInterval(timer);//到了临界点，关掉定时器
            ad.style.display = 'none';//隐藏广告
        }
        time.innerHTML = num + '秒';
    }, 1000);

    //3.主动点击x：马上关掉定时器并隐藏广告
    close.onclick = function() {
        clearInterval(timer);//到了临界点，关掉定时器
        ad.style.display = 'none';//隐藏广告
    }

</script>
</html>